package com.hsy.linemoney.modules.my.gain_and_reward;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.hsy.linemoney.R;
import com.hsy.linemoney.apiservice.AccountService;
import com.hsy.linemoney.apiservice.Callback;
import com.hsy.linemoney.apiservice.PointService;
import com.hsy.linemoney.modules.common.CommonBaseActivityWithSimpleActionBar;
import com.hsy.linemoney.modules.common.EditTextExt;
import com.hsy.linemoney.utils.CommonUtils;
import com.widget.picker.CustomListPickers;

import java.util.ArrayList;
import java.util.Calendar;

/**
 * 利润和奖金
 * Created by MartinKent on 2016/10/24.
 */

public class MyGainAndRewardActivity extends CommonBaseActivityWithSimpleActionBar {
    private TextView serviceType, selectedDurationSpinner, commit;

    private TextView totalPoints;
    private TextView exchangedPoints;
    private TextView exchangedAmountUsd;
    private TextView monthPoints;
    private TextView availablePoints;
    private TextView availableAmounts;
    private EditTextExt toExchangeAmount;

    private AccountService.CashableAccountsResult accountListResult;
    private int selectedAccountWhich = -1;

    private String[] currentSelectedMonth;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_gain_and_reward);
        setTitle(R.string.title_my_points);

        serviceType = F(R.id.service_type);
        serviceType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                AccountService service = new AccountService();
                service.getCashableAccounts(new Callback<AccountService.CashableAccountsResult>() {
                    @Override
                    public void onSuccess(int what, AccountService.CashableAccountsResult result) {
                        accountListResult = result;
                        showListDialog(result.getAccountNameArray(), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                selectedAccountWhich = which;
                                serviceType.setText(accountListResult.getAccountNameArray()[which]);
                                dialog.dismiss();
                            }
                        });
                    }

                    @Override
                    public void onError(int what, int type, String msg, Exception e) {

                    }
                });
            }
        });

        commit = F(R.id.commit);
        commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkThrough()) {
                    String transferAmount = toExchangeAmount.getText().toString();
                    String toAccountId = accountListResult.getValue().getAccounts().get(selectedAccountWhich).getAccount_id();

                    final Snackbar snackbar = Snackbar.make(getRootView(), getString(R.string.txt_you_are_transfer_to_your_account, transferAmount, toAccountId), Snackbar.LENGTH_INDEFINITE);
                    snackbar.show();
                    PointService service = new PointService();
                    service.transferCash(transferAmount, toAccountId, new Callback<PointService.CashTransferResult>() {

                        @Override
                        public void onSuccess(int what, PointService.CashTransferResult result) {
                            snackbar.setText(R.string.txt_transfer_success);
                            snackbar.setDuration(Snackbar.LENGTH_LONG);
                            snackbar.show();
                        }

                        @Override
                        public void onError(int what, int type, String msg, Exception e) {
                            snackbar.setText(R.string.txt_transfer_failed);
                            snackbar.setDuration(Snackbar.LENGTH_LONG);
                            snackbar.show();
                        }
                    });
                }
            }
        });

        selectedDurationSpinner = F(R.id.select_duration);
        selectedDurationSpinner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMonthPicker(new CustomListPickers.PickerSelListener() {
                    @Override
                    public void complete(String[] index, String[] result) {
                        currentSelectedMonth = result;
                        selectedDurationSpinner.setText(result[0] + "/" + result[1]);
                        updateData(result[1] + "/1/" + result[0]);
                    }
                });
            }
        });

        totalPoints = (TextView) findViewById(R.id.total_points);
        exchangedPoints = (TextView) findViewById(R.id.exchanged_points);
        exchangedAmountUsd = (TextView) findViewById(R.id.exchanged_amount_usd);
        monthPoints = (TextView) findViewById(R.id.month_points);
        availablePoints = (TextView) findViewById(R.id.available_points);
        availableAmounts = (TextView) findViewById(R.id.available_amounts);
        toExchangeAmount = (EditTextExt) findViewById(R.id.to_exchange_amount);
        toExchangeAmount.setEnabled(false);

        Calendar calendar = Calendar.getInstance();
        updateData((calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.DATE) + "/" + calendar.get(Calendar.YEAR));
    }

    private boolean checkThrough() {
        if (selectedAccountWhich < 0 || null == currentSelectedMonth || null == accountListResult) {
            showToast(R.string.txt_please_select_cash_account);
            return false;
        }
        return true;
    }

    private void updateData(final String date) {
        showProgressDialog(this);
        PointService service = new PointService();
        service.getUserPointsReport(date, new Callback<PointService.UserPointsReportResult>() {
            @Override
            public void onSuccess(int what, PointService.UserPointsReportResult result) {
                totalPoints.setText(result.getValue().getYear_to_date_total_points());
                exchangedPoints.setText(result.getValue().getYear_to_date_total_cashed_amount());
                exchangedAmountUsd.setText(result.getValue().getYear_to_date_transferred_amount());
                monthPoints.setText(result.getValue().getThis_month_total_points());
                availablePoints.setText(result.getValue().getYear_to_date_cashable_points());
                availableAmounts.setText(result.getValue().getYear_to_date_transferrable_amount());
                toExchangeAmount.setText(result.getValue().getYear_to_date_transferrable_amount());
                hideProgressDialog();
            }

            @Override
            public void onError(int what, int type, String msg, Exception e) {
                hideProgressDialog();
            }
        });
    }

    private void showListDialog(String[] items, DialogInterface.OnClickListener listener) {
        new AlertDialog.Builder(this).setItems(items, listener).show();
    }

    private void showMonthPicker(CustomListPickers.PickerSelListener listener) {
        ArrayList<ArrayList<String>> data = new ArrayList<>();
        data.add(new ArrayList<String>());
        data.add(new ArrayList<String>());

        Calendar calendar = Calendar.getInstance();
        int y = calendar.get(Calendar.YEAR);
        for (int i = 0; i < 50; i++) {
            data.get(0).add("" + (y - i));
        }
        for (int i = 0; i < 12; i++) {
            data.get(1).add("" + (i + 1));
        }

        CustomListPickers customListPicker = new CustomListPickers(this, listener);
        customListPicker.init(getString(R.string.txt_select_month), data, 0, 5, false, "");
        customListPicker.showAtLocation(getRootView(), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

}
